package com.dubbo.server.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dubbo.server.mapper.AdminMapper;
import com.dubbo.server.pojo.Admin;
import com.dubbo.server.vo.AdminVo;
import com.dubbo.server.vo.ErrorResult;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.joda.time.DateTime;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String CACHE_CODE_PREFIX = "ADMIN_CODE_";

    private static final String CACHE_KEY_TOKEN_PREFIX = "MANAGE_TOKEN_";

    @Autowired
    private AdminMapper adminMapper;


    @Value("${jwt.secret}")
    private String secret;

    /**
     * 将验证码存进redis
     *
     * @param uuid
     * @param code
     */
    public void saveVerificationCode(String uuid, String code) {
        String key = CACHE_CODE_PREFIX + uuid;
        //验证码5分钟之后失效(用过就删)
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
    }


    /**
     * 验证账户名 密码生成tocker
     *
     * @param adminVo
     * @return
     */
    public ErrorResult login(AdminVo adminVo) {
        try {
            if (adminVo.getUsername() == null && adminVo.getPassword() == null) {
                return ErrorResult.builder().token(null).errCode("0003").errMessage("账户或者密码不合法！").build();
            }

            //校验验证码
            String key = CACHE_CODE_PREFIX + adminVo.getUuid();

            String code = this.redisTemplate.opsForValue().get(key);


            if (!StrUtil.equals(code, adminVo.getVerificationCode())) {
                return ErrorResult.builder().token(null).errCode("0001").errMessage("验证码错误！").build();
            }

            //把原有的验证码删除掉
            this.redisTemplate.delete(key);

            //根据用户名查询admin对象
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("username", adminVo.getUsername()).eq("password", adminVo.getPassword());
            Admin admin = adminMapper.selectOne(wrapper);
            //对比密码是否正确
            if (admin == null) {
                return ErrorResult.builder().token(null).errCode("0003").errMessage("账户或者密码出错！").build();
            }

            Map<String, Object> claims = new HashMap<String, Object>();
            claims.put("username", admin.getUsername());
            claims.put("id", admin.getId());

            // 生成token
            String token = Jwts.builder()
                    .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                    .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                    .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                    .compact();

            return ErrorResult.builder().token(token).errCode("0001").errMessage("登录成功！").build();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("token异常.", e);
            return null;
        }
    }


    //    校验token方法
    public Admin queryUserByToken(String token) {

        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

            Admin admin = new Admin();
            admin.setId(Integer.valueOf(body.get("id").toString()));
            admin.setUsername(body.get("username").toString());


            //查询数据库
            Admin admin01 = adminMapper.selectById(admin.getId());
            return admin01;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {
            System.out.println("token = " + token);
            log.error("token不合法！ token = " + token, e);
        }
        return null;
    }


//    /**
//     * 从数据库查询个人信息
//     *
//     * @param id
//     * @return
//     */
//    public Admin getById(Integer id) {
//        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
//        wrapper.eq("id", id);
//        Admin admin = adminMapper.selectOne(wrapper);
//        return admin;
//    }
}
